package cn.liucl.code.blogsTest;

import cn.liucl.code.blogsTest.entry.Address;
import cn.liucl.code.blogsTest.entry.User;

import java.util.Optional;

/**
 * @description:
 * @author: liuchengliang01
 * @time: 2023/3/2 17:34
 */
public class OptionalDemo {

    //以前写法
//    public String getCity(User user)  throws Exception{
//        if(user!=null){
//            if(user.getAddress()!=null){
//                Address address = user.getAddress();
//                if(address.getCity()!=null){
//                    return address.getCity();
//                }
//            }
//        }
//        throw new Excpetion("取值错误");
//    }

    //JAVA8写法
    public String getCity(User user) throws Exception {
        return Optional.ofNullable(user)
                .map(User::getAddress)
                .map(Address::getCity)
                .orElseThrow(() -> new Exception("取指错误"));
    }

    //    以前写法
    public static void main(String[] args) {
        User user = new User();
        if (user != null) {
//            dosomething(user);
        }
        // JAVA8写法
        Optional.ofNullable(user).ifPresent(u -> {
//           dosomething(u);
        });
    }
    //以前写法
    public User getUser1(User user) throws Exception {
        if (user != null) {
            String name = user.getName();
            if ("zhangsan".equals(name)) {
                return user;
            } else {
                user = new User();
                user.setName("zhangsan");
                return user;
            }
        } else {
            user = new User();
            user.setName("zhangsan");
            return user;
        }
    }
    //java8写法
    public User getUser2(User user) {
        return Optional.ofNullable(user)
                .filter(u -> "zhangsan".equals(u.getName()))
                .orElseGet(() -> {
                    User user1 = new User();
                    user1.setName("zhangsan");
                    return user1;
                });
    }

}
